package cn.didi.feidi.androidorder.fragment;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.bumptech.glide.Glide;
import com.google.gson.reflect.TypeToken;
import com.jzxiang.pickerview.TimePickerDialog;
import com.jzxiang.pickerview.data.Type;
import com.jzxiang.pickerview.listener.OnDateSetListener;

import org.greenrobot.greendao.async.AsyncOperation;
import org.greenrobot.greendao.async.AsyncOperationListener;
import org.greenrobot.greendao.async.AsyncSession;
import org.greenrobot.greendao.query.QueryBuilder;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import cn.didi.feidi.androidorder.Constants;
import cn.didi.feidi.androidorder.OrderApplication;
import cn.didi.feidi.androidorder.R;
import cn.didi.feidi.androidorder.activity.personal.PersonFindBackPayPasswordGuideActivity;
import cn.didi.feidi.androidorder.activity.personal.PersonReceiveAddressActivity;
import cn.didi.feidi.androidorder.activity.personal.PersonWalletPayPasswordFirstSetActivity;
import cn.didi.feidi.androidorder.api.Api;
import cn.didi.feidi.androidorder.api.ApiResponse;
import cn.didi.feidi.androidorder.api.ErrorEvent;
import cn.didi.feidi.androidorder.assembly.CommomDialog;
import cn.didi.feidi.androidorder.assembly.FeiDiInputPasswordFragmentDialog;
import cn.didi.feidi.androidorder.assembly.SelectPayWayFragmentDialog;
import cn.didi.feidi.androidorder.assembly.WaterShowView;
import cn.didi.feidi.androidorder.core.ActionCallbackListener;
import cn.didi.feidi.androidorder.core.AppActionRequest;
import cn.didi.feidi.androidorder.databinding.FragmentConfirmOrderBinding;
import cn.didi.feidi.androidorder.db.UserAddressDao;
import cn.didi.feidi.androidorder.manager.UserManager;
import cn.didi.feidi.androidorder.model.AuthResult;
import cn.didi.feidi.androidorder.model.OrderUser;
import cn.didi.feidi.androidorder.model.PayResult;
import cn.didi.feidi.androidorder.model.ShoppingCar;
import cn.didi.feidi.androidorder.model.UserAddress;
import cn.didi.feidi.androidorder.util.AppUtil;
import cn.didi.feidi.androidorder.util.MD5Util;

/**
 * Created by jinxiong on 2017/8/22.
 */

public class ConfirmOrderFragment extends FeidiBaseFragment {

    public static final int REQUEST_CODE = 1;
    public static final int RESULT_CODE = 2;
    public static final int SOURCE = 2;
    private static final int SDK_PAY_FLAG = 1;
    private static final int SDK_AUTH_FLAG = 2;

    private static final String TAG = "ConfirmOrderFragment";
    FragmentConfirmOrderBinding binding;
    AsyncSession asyncSession;
    ArrayList<ShoppingCar> shoppingCars;
    UserAddress userAddress;
    float goodsPrice;//商品的总价格
    float totalPrice;//整个订单的总价格
    private long startTime;//开始时间
    private long endTime;//结束时间
    private boolean isUrgent;//是否是加急订单
    private int urgentMoney;//加急的配送费
    private float blankBucketDeposit;//补交押金
    private int blankBucketCount;//空桶数目 用户已有空桶数
    private int waterBucketCount;//定的水桶数
    private boolean successSubmitOrder;//成功提交订单，用于返回刷新购物车


    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    Log.d(TAG, resultInfo);
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        makeToast("支付成功");

                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        makeToast("支付失败");
                    }


                    setResultToActivity();


                    break;
                }
                case SDK_AUTH_FLAG: {
                    @SuppressWarnings("unchecked")
                    AuthResult authResult = new AuthResult((Map<String, String>) msg.obj, true);
                    String resultStatus = authResult.getResultStatus();

                    // 判断resultStatus 为“9000”且result_code
                    // 为“200”则代表授权成功，具体状态码代表含义可参考授权接口文档
                    if (TextUtils.equals(resultStatus, "9000") && TextUtils.equals(authResult.getResultCode(), "200")) {
                        // 获取alipay_open_id，调支付时作为参数extern_token 的value
                        // 传入，则支付账户为该授权账户
                        makeToast("授权成功");
                    } else {
                        // 其他状态值则为授权失败
                        makeToast("授权失败");

                    }
                    break;
                }
                default:
                    break;
            }
        }


    };

    /**
     * 与activity关联，后面可考虑单例模式
     *
     * @param bundle
     * @return
     */
    public static ConfirmOrderFragment newInstance(Bundle bundle) {
        ConfirmOrderFragment fragment = new ConfirmOrderFragment();
        if (bundle != null)
            fragment.setArguments(bundle);
        return fragment;
    }

    //计算这个订单的总价
    private float calculateTotalMoney() {
        totalPrice = goodsPrice + urgentMoney + blankBucketDeposit;
        binding.confirmOrderTotalPriceTv.setText("" + totalPrice);
        return totalPrice;
    }


    @Override
    protected View initFragment(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        binding = DataBindingUtil.inflate(inflater, R.layout.fragment_confirm_order, container, false);
        return binding.getRoot();
    }

    @Override
    protected void initViews(View rootView) {
    }

    @Override
    protected void initData() {

        asyncSession = OrderApplication.getDaoSession().startAsyncSession();

        //数据库回调
        asyncSession.setListenerMainThread(new AsyncOperationListener() {
            @Override
            public void onAsyncOperationCompleted(AsyncOperation operation) {
                if (operation.isFailed()) {
//                    Toast.makeText(mActivity, "获取地址信息错误", Toast.LENGTH_SHORT).show();
                    Log.d(TAG, "onAsyncOperationCompleted: 获取地址信息失败");
                    return;
                }

                if (operation.getResult() != null) {
                    userAddress = (UserAddress) operation.getResult();
                    binding.setUserAddress(userAddress);
                }


            }
        });
        ///从数据库拿默认的地址
        asyncSession.queryUnique(QueryBuilder.internalCreate(OrderApplication.getDaoSession().getDao(UserAddress.class))
                .where(UserAddressDao.Properties.DefaultAddress.eq(true), UserAddressDao.Properties.UserId.eq(UserManager.getUserId()))
                .build());


        Intent intent = getActivity().getIntent();
        shoppingCars = (ArrayList<ShoppingCar>) intent.getSerializableExtra("shoppingCars");
        goodsPrice = intent.getFloatExtra("goodsPrice", -1);//商品价格

        if (goodsPrice == -1 || shoppingCars == null || shoppingCars.size() == 0) {
            Toast.makeText(mActivity, "获取数据错误", Toast.LENGTH_SHORT).show();
            getActivity().finish();
        }

        binding.setTotalPrice(goodsPrice);
        int size = shoppingCars.size();

        for (int i = 0; i < size; i++) {
            ShoppingCar shop = shoppingCars.get(i);
            WaterShowView view = new WaterShowView(getActivity());
            view.setShoppingCar(shop);
            Glide.with(this)
                    .load(shop.getPicUrl())
                    .placeholder(R.drawable.logo)
                    .into(view.getImageView());

            binding.confirmOrderWaterContainerLl.addView(view);
            waterBucketCount += shop.getBuyCount();
        }

        blankBucketDeposit = 50 * waterBucketCount;//补交的空桶押金
        binding.confirmOrderDepositTv.setText("¥" + blankBucketDeposit);
        calculateTotalMoney();//计算出总价格


    }

    @Override
    protected void addListener() {

        binding.confirmOrderAddressParentLl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Intent intent = new Intent(ConfirmOrderFragment.this.getActivity(), PersonReceiveAddressActivity.class);
                intent.putExtra("source", SOURCE);
                startActivityForResult(intent, REQUEST_CODE);
            }
        });


        binding.confirmOrderDeliverTimeRl.setOnClickListener(
                new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                        if (isMultiplicationClick()) {
                            return;
                        }

                        showTimeSelectorDialog();
                    }

                    //展示时间选择器
                    private void showTimeSelectorDialog() {
                        final long currentTime = System.currentTimeMillis();


                        //最早时间选择
                        TimePickerDialog mDialogAll = new TimePickerDialog.Builder()
                                .setType(Type.MONTH_DAY_HOUR_MIN)
                                .setCallBack(new OnDateSetListener() {
                                    @Override
                                    public void onDateSet(TimePickerDialog timePickerView, long millseconds) {
                                        startTime = millseconds;


                                        //结束时间dialog
                                        TimePickerDialog dialog = new TimePickerDialog.Builder()
                                                .setType(Type.MONTH_DAY_HOUR_MIN)
                                                .setCallBack(new OnDateSetListener() {
                                                    @Override
                                                    public void onDateSet(TimePickerDialog timePickerView, long millseconds) {


                                                        endTime = millseconds;
                                                        if (startTime == 0) {
                                                            Toast.makeText(mActivity, "没有选择开始时间", Toast.LENGTH_SHORT).show();
                                                            restoreDefault();
                                                            return;
                                                        }

                                                        if (startTime > endTime || endTime < System.currentTimeMillis()) {
                                                            Toast.makeText(mActivity, "送达时间选择有误", Toast.LENGTH_SHORT).show();
                                                            restoreDefault();
                                                            return;
                                                        }
                                                        changeView();

                                                    }

                                                    //对应view 的改变和相关变量改变
                                                    private void changeView() {
                                                        //加急,
                                                        if ((startTime - currentTime) <= 3 * 60 * 1000 && (endTime - startTime) <= 2 * 60 * 60 * 1000) {
                                                            binding.confirmOrderDeliverTimeUrgentTv.setVisibility(View.VISIBLE);
                                                            binding.confirmOrderDeliverFeeUrgentTv.setVisibility(View.VISIBLE);
                                                            binding.confirmOrderDeliverFeeUrgentPriceTv.setText("¥" + waterBucketCount);

                                                            urgentMoney = waterBucketCount;
                                                            calculateTotalMoney();
                                                            Toast.makeText(mActivity, "时间段太短,为加急订单", Toast.LENGTH_SHORT).show();


                                                            isUrgent = true;
                                                        } else {

                                                            urgentMoney = 0;
                                                            calculateTotalMoney();

                                                            isUrgent = false;
                                                            binding.confirmOrderDeliverTimeUrgentTv.setVisibility(View.GONE);
                                                            binding.confirmOrderDeliverFeeUrgentTv.setVisibility(View.GONE);
                                                            binding.confirmOrderDeliverFeeUrgentPriceTv.setText("");
                                                        }
                                                        Log.d(TAG, "onDateSet: " + (endTime - startTime));
                                                        binding.confirmOrderDeliverTimeTv.setText(
                                                                AppUtil.dateTransferString(startTime, Constants.START_TIME_FORMAT) + "-" +
                                                                        AppUtil.dateTransferString(endTime, Constants.START_TIME_FORMAT));
                                                    }

                                                })

                                                .setCyclic(false)
                                                .setTitleStringId("最晚送达时间")
                                                .setThemeColor(Color.parseColor("#347cf1"))
                                                .setMinMillseconds(startTime)
                                                .setMaxMillseconds(startTime + 7 * 24 * 60 * 60 * 1000)
                                                .setCurrentMillseconds(startTime)
                                                .build();
                                        dialog.show(getChildFragmentManager(), "endTime");


                                    }
                                })
                                .setCyclic(false)
                                .setTitleStringId("最早送达时间")
                                .setMaxMillseconds(currentTime + 7 * 24 * 60 * 60 * 1000)
                                .setThemeColor(Color.parseColor("#347cf1"))
                                .setMinMillseconds(currentTime)
                                .setCurrentMillseconds(currentTime)
                                .build();

                        mDialogAll.show(getChildFragmentManager(), "startTime");
                    }

                }
        );


        binding.confirmOrderInputBlankBucketEt.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {

                String inputString = s.toString().trim();
                if (inputString.length() == 0) {
                    blankBucketCount = 0;
                    blankBucketDeposit = (waterBucketCount - blankBucketCount) * 50;
                    calculateTotalMoney();

                    binding.confirmOrderDepositTv.setText("¥" + blankBucketDeposit);
                    return;
                }

                if (!TextUtils.isDigitsOnly(inputString)) {
                    binding.confirmOrderInputBlankBucketEt.setText("");
                    return;
                }

                try {

                    int count = Integer.parseInt(inputString);
                    if (count > waterBucketCount) {
                        binding.confirmOrderInputBlankBucketEt.setText("");
                        Toast.makeText(mActivity, "空桶数大于水桶数", Toast.LENGTH_SHORT).show();
                        return;
                    }

                    blankBucketCount = count;
                    blankBucketDeposit = (waterBucketCount - blankBucketCount) * 50;
                    calculateTotalMoney();
                    binding.confirmOrderDepositTv.setText("¥" + blankBucketDeposit);

                } catch (NumberFormatException e) {
                    return;
                }


            }
        });

        binding.confirmOrderSubmitOrderTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                //判断参数的合法性
                if (judgeParameters()) return;

                //为参数赋值
                HashMap<String, String> parameters = addValueForParameters();

                executeRequest(new AppActionRequest<>(Api.PLACE_AN_ORDER, parameters, new TypeToken<ApiResponse<OrderUser>>() {
                }.getType(),
                        new ActionCallbackListener<OrderUser>() {
                            @Override
                            public void onSuccess(String message, OrderUser data) {
                                Log.d(TAG, "onSuccess: " + data.getOrderUserId());
                                //  : 2017/8/27 暂时直接关闭掉这个activity 后续再处理 ---jinXiong

                                payMoney(data);
                                successSubmitOrder = true;

                            }

                            @Override
                            public void onFailure(int errorEvent, String message) {
                                Log.d(TAG, "onFailure: " + message);
                                Toast.makeText(mActivity, "下订单出错", Toast.LENGTH_SHORT).show();
                            }
                        }));


            }

            /**
             * @return 请求参数
             */
            @NonNull
            private HashMap<String, String> addValueForParameters() {
                String remark = binding.confirmOrderRemarkEt.getText().toString().trim();

                HashMap<String, String> parameters = new HashMap<>();
                parameters.put("userId", UserManager.getUserId());
                parameters.put("token", UserManager.getToken());
                parameters.put("amount", String.valueOf(totalPrice));
                parameters.put("userAddressId", userAddress.getUserAddressId());
                parameters.put("urgentPrice", String.valueOf(urgentMoney));
                parameters.put("isOrdered", "0");
                parameters.put("startTime", long2String(startTime));
                parameters.put("endTime", long2String(endTime));

                parameters.put("deposit", String.valueOf(blankBucketDeposit));
                parameters.put("remark", remark);

                int size = shoppingCars.size();
                for (int i = 0; i < size; i++) {
                    ShoppingCar shoppingCar = shoppingCars.get(i);
                    parameters.put("orderWaBuOrUsList[" + i + "].bucketTypeId", String.valueOf(shoppingCar.getBucketTypeId()));
                    parameters.put("orderWaBuOrUsList[" + i + "].quantity", String.valueOf(shoppingCar.getBuyCount()));
                }

                parameters.put("orderBlBuOrUsList[0].bucketTypeId", "" + shoppingCars.get(0).getBucketTypeId());

                parameters.put("orderBlBuOrUsList[0].quantity", blankBucketCount + "");
                return parameters;
            }

            //判断参数的合法性
            private boolean judgeParameters() {
                if (isMultiplicationClick()) {
                    return true;
                }

                if (startTime == 0 && endTime == 0) {
                    startTime = System.currentTimeMillis();
                    endTime = startTime + 2 * 60 * 60 * 1000;
                } else {
                    if (startTime > endTime || endTime < System.currentTimeMillis()) {
                        restoreDefault();
                        Toast.makeText(mActivity, "配送时间有误", Toast.LENGTH_SHORT).show();
                        return true;
                    }
                }

                if (userAddress == null) {
                    Toast.makeText(mActivity, "未选择地址", Toast.LENGTH_SHORT).show();
                    return true;
                }

                if (waterBucketCount < blankBucketCount || (waterBucketCount - blankBucketCount) * 50 != blankBucketDeposit) {
                    Toast.makeText(mActivity, "空桶数目出错", Toast.LENGTH_SHORT).show();
                    return true;
                }


                if (totalPrice != goodsPrice + urgentMoney + blankBucketDeposit) {
                    Toast.makeText(mActivity, "订单价格出错", Toast.LENGTH_SHORT).show();
                    return true;
                }
                return false;
            }
        });


    }


    /**
     * 将选择的时间 转为服务器合适的时间格式字符串
     *
     * @param time
     * @return
     */
    public String long2String(long time) {

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss ", Locale.ENGLISH);
//        Log.d(TAG, "long2String: " + simpleDateFormat.format(new Date(time)) + "+0800 (CST)");
        return simpleDateFormat.format(new Date(time)) + "+0800 (CST)";


    }

    /**
     * 还原 选择送达时间
     */
    private void restoreDefault() {
        startTime = 0;
        endTime = 0;
        binding.confirmOrderDeliverTimeTv.setText("默认两小时内送达");
        isUrgent = false;
        urgentMoney = 0;
        calculateTotalMoney();
        binding.confirmOrderDeliverTimeUrgentTv.setVisibility(View.GONE);
        binding.confirmOrderDeliverFeeUrgentTv.setVisibility(View.GONE);
        binding.confirmOrderDeliverFeeUrgentPriceTv.setText("");
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == REQUEST_CODE) {

            switch (resultCode) {

                //地址选择回调
                case RESULT_CODE: {
                    userAddress = (UserAddress) data.getSerializableExtra("userAddress");
                    binding.setUserAddress(userAddress);
                    Log.d(TAG, "onActivityResult: " + userAddress.getAddress());
                    break;
                }

            }

        }

    }

    /**
     * 支付订单
     *
     * @param orderUser
     */
    private void payMoney(final OrderUser orderUser) {

        final SelectPayWayFragmentDialog selectPayWayFragmentDialog = new SelectPayWayFragmentDialog();
        selectPayWayFragmentDialog.setAliPayListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isMultiplicationClick()) {
                    return;
                }
                selectPayWayFragmentDialog.dismiss();

                payMoneyByAli(orderUser);
            }
        }).setWalletListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (isMultiplicationClick()) {
                    return;
                }
                selectPayWayFragmentDialog.dismiss();
                payMoneyByWallet(orderUser);
            }
        }).setCloseListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                selectPayWayFragmentDialog.dismiss();
                setResultToActivity();

            }
        }).setTipVisible().setCloseActivityCallback(new SelectPayWayFragmentDialog.CloseActivityCallback() {
            @Override
            public void closeCallback() {

                setResultToActivity();
            }
        });

        Bundle bundle = new Bundle();
        bundle.putDouble("amount", orderUser.getAmount());
        selectPayWayFragmentDialog.setArguments(bundle);

        selectPayWayFragmentDialog.show(getChildFragmentManager(), "selectPayWay");

    }


    /**
     * 将数据返回给上一个Activity  ，用于从购物车删除已经订购的商品
     */
    private void setResultToActivity() {

        Activity activity = getActivity();
        Intent intent = new Intent();
        intent.putExtra("success", successSubmitOrder);
        activity.setResult(2, intent);
        getActivity().finish();

    }


    /**
     * 支付订单 支付宝支付
     *
     * @param orderUser
     */
    private void payMoneyByAli(OrderUser orderUser) {

        Map<String, String> params = new HashMap<>();

        params.put("userId", UserManager.getUserId());
        params.put("token", UserManager.getToken());
        params.put("orderUserId", orderUser.getOrderUserId());
        params.put("amount", String.valueOf(orderUser.getAmount()));

        executeRequest(new AppActionRequest<String>(Api.GET_ALIPAY_SIGNED_ORDER_USER, params,
                new TypeToken<ApiResponse<String>>() {
                }.getType(), new ActionCallbackListener<String>() {
            @Override
            public void onSuccess(String message, final String data) {
                if (data != null) {
                    Runnable payRunnable = new Runnable() {

                        @Override
                        public void run() {
                            PayTask alipay = new PayTask(mActivity);
                            Map<String, String> result = alipay.payV2(data, true);
                            Log.i("jinxiong", result.toString());

                            Message msg = Message.obtain();
                            msg.what = SDK_PAY_FLAG;
                            msg.obj = result;
                            mHandler.sendMessage(msg);
                        }
                    };
                    // 必须异步调用
                    Thread payThread = new Thread(payRunnable);
                    payThread.start();
                } else {
                    makeToast("success" + message);
                    Log.d(TAG, message);
                }
            }

            @Override
            public void onFailure(int errorEvent, String message) {
                Log.d(TAG, "errorEvent:" + errorEvent + "message=" + message);

                switch (errorEvent) {
                    default:
                        makeToast("未知错误");
                        setResultToActivity();
                        break;
                }
            }
        }));
    }


    /**
     * 支付订单 钱包支付
     *
     * @param orderUser
     */
    private void payMoneyByWallet(final OrderUser orderUser) {
        if (!UserManager.isSetPayPassword()) {//未设置支付密码
            new CommomDialog(getContext(), R.style.dialog, "您尚未设置支付密码", new CommomDialog.OnCloseListener() {
                @Override
                public void onClick(Dialog dialog, boolean confirm) {
                    if (confirm) {
                        makeToast("现在设置");
                        Intent intent = new Intent(getContext(), PersonWalletPayPasswordFirstSetActivity.class);
                        getContext().startActivity(intent);
                        dialog.dismiss();
                    }
                }
            }, true, true).setPositiveButton("现在设置").show();
        } else {
            final FeiDiInputPasswordFragmentDialog inputPasswordFragmentDialog = new FeiDiInputPasswordFragmentDialog();

            inputPasswordFragmentDialog.setCallback(new FeiDiInputPasswordFragmentDialog.Callback() {
                @Override
                public void inputCallback(String inputString) {
                    //输入完 6 位密码后自动回调 发起支付
                    Map<String, String> params = new HashMap<>();

                    params.put("userId", UserManager.getUserId());
                    params.put("token", UserManager.getToken());
                    params.put("orderUserId", orderUser.getOrderUserId());
                    params.put("payPwd", MD5Util.GetMD5Code32Bit(inputString));

                    executeRequest(new AppActionRequest<List<OrderUser>>(Api.FEIDI_PAY_PAY_ORDER_USER, params,
                            new TypeToken<ApiResponse<List<OrderUser>>>() {
                            }.getType(), new ActionCallbackListener<List<OrderUser>>() {
                        @Override
                        public void onSuccess(String message, final List<OrderUser> data) {
                            makeToast("支付成功");
                            inputPasswordFragmentDialog.dismiss();
                            setResultToActivity();
                        }

                        @Override
                        public void onFailure(int errorEvent, String message) {
                            Log.d(TAG, "errorEvent:" + errorEvent + "message=" + message);
                            switch (errorEvent) {
                                case ErrorEvent.WRONG_PAYPWD:
//                                  支付密码错误
                                    makeToast(message);
                                    inputPasswordFragmentDialog.clearInput();
                                    break;
                                case ErrorEvent.WRONG_PAY_ORDER_NO_MONEY:
                                    makeToast("飞滴钱包没钱");
                                    inputPasswordFragmentDialog.dismiss();
                                    break;
                                case ErrorEvent.UNSET_PAYPWD:
                                    makeToast("支付密码未设置");
                                    inputPasswordFragmentDialog.dismiss();
                                    break;
                                case ErrorEvent.FEIDI_WALLET_PAY_PASSWORD_BEYOND_FIVE_TIME_IN_ONE_HOUR:
                                    new CommomDialog(getContext(), R.style.dialog, "密码错误次数已达上限\n请一小时后重试", new CommomDialog.OnCloseListener() {
                                        @Override
                                        public void onClick(Dialog dialog, boolean confirm) {
                                            if (confirm){
                                                dialog.dismiss();
                                                inputPasswordFragmentDialog.dismiss();
                                            }
                                        }
                                    },true,true).setPositiveButton("好的").show();
                                    break;
                                default:
                                    makeToast("未知错误");
                                    inputPasswordFragmentDialog.dismiss();
                                    break;
                            }
                        }
                    }));
                }
            }).setForgetPassworListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //忘记密码
                    Intent intent = new Intent(getContext(), PersonFindBackPayPasswordGuideActivity.class);
                    startActivity(intent);
                }
            }).setCloseDialogListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    setResultToActivity();
                }
            });

            inputPasswordFragmentDialog.show(getChildFragmentManager(), "payMoneyByWallet");
        }
    }

}
